package com.quanyan.common.utils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import com.thoughtworks.xstream.io.xml.XppDriver;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 处理xml的工具类
 * Created by Zheng.Ke
 * Date 2016/8/8.
 */
public class XmlUtils {

    /**
     * xml格式字符串转JAVA对象（注解）
     * @param xmlStr
     * @param entityClazz
     * @param <T>
     * @return
     */
    public static <T> T xmlStrToEntity(String xmlStr, Class<T> entityClazz) {
        XStream xStream = new XStream();
        xStream.processAnnotations(entityClazz);
        xStream.ignoreUnknownElements();
        T t = (T) xStream.fromXML(xmlStr);
        return t;
    }

    /**
     * 对象转xml字符串（注解）
     * @param obj
     * @return
     */
    public static String toXmlStr(Object obj) {
        XStream xstream = new XStream(new XppDriver(new XmlFriendlyNameCoder("_-", "_")));
        xstream.processAnnotations(obj.getClass());
        return xstream.toXML(obj);
    }

    /**
     * xml格式字符串转成map
     * @param xml
     * @return
     */
    public static Map<String, String> xmlStrToMap(String xml) {
        Map<String, String> map = new HashMap<>();
        if (xml == null) {
            return map;
        }
        try {
            Document document = DocumentHelper.parseText(xml);
            Element nodeElement = document.getRootElement();
            List node = nodeElement.elements();
            for (Iterator it = node.iterator(); it.hasNext(); ) {
                Element elm = (Element) it.next();
                map.put(elm.getQualifiedName(), elm.getText());
            }
        } catch (Exception e) {
        }
        return map;
    }
}
